from PyQt5.QtWidgets import QDialog, QMessageBox
from PyQt5.QtCore import pyqtSignal
from signUpUi import *
from server import *


class SignUpDlg(QDialog, Ui_signUpDlg):
    saved = pyqtSignal(str)

    def __init__(self):
        super(QDialog, self).__init__()
        self.setupUi(self)
        self.pb_submit.clicked.connect(self._add_new_user)
        self.pb_cancel.clicked.connect(self._cancel)

    def _add_new_user(self):
        grade_list = (6, 5, 4, 3, 2, 1, 13, 12, 11)
        user = User()
        server = Server()
        user.phone_number = self.line_edit_phone_number.text()
        if len(user.phone_number) != 11:
            QMessageBox.information(self, self.tr('Error'), self.tr('Please input a correct phone number!'))
            return
        user.user_name = self.line_editor_user_name.text()
        if len(user.user_name) == 0:
            QMessageBox.information(self, self.tr('Error'), self.tr('User name shouldn\'t be null!'))

        index = self.combobox_grade.currentIndex()
        user.grade = grade_list[index]

        if server.connect_to_server() is True:
            ret = server.get_user_info(user.phone_number)
            if ret is not None:
                QMessageBox.information(self, self.tr('Error'), self.tr('The phone number is existed!'))
            server.add_new_user(user)
            self.close()
            self.saved.emit(user.phone_number)
            QMessageBox.information(self, self.tr('Notice'), self.tr('Add new user Success!'))
        else:
            QMessageBox.information(self, self.tr('Error'), self.tr('Add new user fail!'))

    def _cancel(self):
        self.close()
